package com.dily.study.springMVC;

import com.dily.study.springMVC.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * Date: 2022-07-01 星期五
 * Time: 15:56
 * Author: Dily_Su
 * Remark: Spring MVC 创建 Servlet
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        // 加载 Spring web config
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        // 设置父容器
        AnnotationConfigWebApplicationContext parent = new AnnotationConfigWebApplicationContext();
        parent.register(AppConfig.class);
        context.setParent(parent);

        // 新建一个 Servlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        // 设置 Servlet 名称
        ServletRegistration.Dynamic registration = servletContext.addServlet("app",servlet);
        // 是否在启动时加载
        registration.setLoadOnStartup(1);
        // Servlet 对应的路径
        registration.addMapping("/app/*");
    }
}
